/*
 *
 *  Copyright (C) THL A29 Limited, a Tencent company. All rights reserved.
 *  SPDX-License-Identifier: Apache-2.0
 *
 */
import React, {useCallback, useContext, useEffect, useState} from 'react';
import {
    Button,
    Card,
    Justify,
    Layout,
    Modal,
    PagingQuery,
    SearchBox,
    Table,
    TableColumn,
    Text,
    Radio
} from 'tea-component';
import {IChainOrgItem} from 'src/common/apis/chains/interface';
import {formatDate} from 'src/utils/date';
import {
    getAddOrgList,
    useFetchChainOrgList, useFetchCreateOrg,
    useFetchRemoveOrganizations
} from 'src/common/apis/chains/hooks';
import {ChainDetailContext} from '../chain-detail';
import {PAGE_SIZE_OPTIONS} from 'src/utils/common';
import GlossaryGuide from 'src/common/components/glossary-guide';


const {Content} = Layout;
const {pageable, autotip} = Table.addons;

export function ChainOrganization() {
    const [searchValue, setSearchValue] = useState<string>('');
    const [searchValueInput, setSearchValueInput] = useState<string>('');
    const [pageQuery, setPageQuery] = useState<Required<PagingQuery>>({pageSize: 10, pageIndex: 1});
    const {chainId} = useContext(ChainDetailContext);
    const {list, totalCount, fetch} = useFetchChainOrgList();
    const {fetchRemoveOrg} = useFetchRemoveOrganizations();
    const {fetchCreateOrg} = useFetchCreateOrg();

    useEffect(() => {
        if (!chainId) {
            return;
        }
        fetch({
            ChainId: chainId,
            PageNum: pageQuery.pageIndex - 1,
            PageSize: pageQuery.pageSize,
            OrgName: searchValue,
        });
    }, [fetch, searchValue, chainId, pageQuery]);

    const defaultColumn: TableColumn<IChainOrgItem>[] = [
        {
            key: 'OrgId',
            header: '组织ID',
        },
        {
            key: 'OrgName',
            header: '组织名称',
        },
        {
            key: 'CreateTime',
            header: '创建时间',
            render: ({CreateTime}) => formatDate(CreateTime),
        },
        {
            key: 'NodeNum',
            header: <GlossaryGuide title="节点数"/>,
            // eslint-disable-next-line react/display-name
            render: ({NodeNum}: IChainOrgItem) => <Text>{NodeNum}</Text>,
        },
        {
            key: 'Action',
            header: '操作',
            render: (record) => (
                <>
                    <Button
                        type="link"
                        onClick={() => {
                            fetchDeleteCert({
                                ChainId: chainId,
                                OrgId: record.OrgId,
                                Type: 1,
                                Reason: `删除组织${record.OrgId}`
                            });
                        }}
                    >
                        删除
                    </Button>
                </>
            ),
        },
    ];

    const fetchList = useCallback(() => {
        if (!chainId) {
            return;
        }
        fetch({
            ChainId: chainId,
            PageNum: pageQuery.pageIndex - 1,
            PageSize: pageQuery.pageSize,
            OrgName: searchValue,
        });
    }, [fetch, searchValue, pageQuery]);
    const fetchDeleteCert = useCallback(
        (param) => {
            fetchRemoveOrg(param).then(() => {
                fetchList();
            });
        },
        [fetchList],
    );
    const fetchAddOrg = useCallback(
        (param) => {
            fetchCreateOrg(param).then(() => {
                fetchList();
            });
        },
        [fetchList],
    );

    const [OrgVisible, setOrgVisible] = useState(false);

    const handleInstallClick = useCallback(() => {
        setOrgVisible(true);
    }, []);

    return (
        <>
            <Layout>
                <Content>
                    <Content.Header title="区块链管理/组织信息"/>
                    <Content.Body full>
                        <Justify
                            left={
                                <Button type={'primary'} onClick={handleInstallClick}>
                                    新增组织
                                </Button>
                            }
                            right={
                                <SearchBox
                                    placeholder="请输入组织名搜索"
                                    size="l"
                                    value={searchValueInput}
                                    onChange={(value) => setSearchValueInput(value)}
                                    onSearch={(value) => setSearchValue(value ?? '')}
                                    onClear={() => setSearchValue('')}
                                />
                            }
                        />
                        <Card className="tea-mt-5n">
                            <Table
                                recordKey="Id"
                                records={list}
                                columns={defaultColumn}
                                addons={[
                                    pageable({
                                        recordCount: totalCount,
                                        pageIndex: pageQuery.pageIndex,
                                        pageSize: pageQuery.pageSize,
                                        pageSizeOptions: PAGE_SIZE_OPTIONS,
                                        onPagingChange: ({pageIndex, pageSize}) =>
                                            setPageQuery({pageIndex: pageIndex ?? 1, pageSize: pageSize ?? 10}),
                                    }),
                                    autotip({
                                        emptyText: '暂无数据',
                                        isFound: !!searchValue.length,
                                        onClear: () => {
                                            setSearchValue('');
                                            setSearchValueInput('');
                                        },
                                    }),
                                ]}
                            />
                        </Card>
                        <OrgModal
                            visible={OrgVisible}
                            close={() => setOrgVisible(false)}
                            onSubmit={(params: any) => {
                                fetchAddOrg(params)
                                setOrgVisible(false)
                            }}
                        />
                    </Content.Body>
                </Content>
            </Layout>
        </>
    );
}

function OrgModal({visible, close, onSubmit}: any) {
    const {chainId} = useContext(ChainDetailContext);
    const [orgList, setOrgList] = useState<any>([]);
    const [orgId, setOrgId] = useState('');

    useEffect(() => {
        if (visible) {
            getAddOrgList({ChainId: chainId}).then(res => {
                setOrgList(res);
            });
        }
    }, [visible, chainId]);

    const handleSubmit = () => {
        onSubmit({ChainId: chainId, OrgId: orgId, Type: 0, Reason: `新增组织${orgId}`});
    };

    return (
        <>
            <Modal visible={visible} caption="新增组织" onClose={close}>
                <Modal.Body>
                    <Radio.Group
                        value={orgId}
                        onChange={value => setOrgId(value)}
                        layout="column"
                    >
                        {orgList.map((item: any) => (
                            <Radio key={item.OrgId} name={item.OrgId}>
                                {item.OrgName}
                            </Radio>
                        ))}
                    </Radio.Group>
                </Modal.Body>
                <Modal.Footer>
                    <Button
                        type="primary"
                        onClick={handleSubmit}
                        disabled={!visible || !orgId}
                    >
                        确定
                    </Button>
                    <Button type="weak" onClick={close}>
                        取消
                    </Button>
                </Modal.Footer>
            </Modal>
        </>
    );
}
